import json


class DeviceCtlDTO:
    """
    DeviceCtlDTO: 设备控制数据传输对象,可以解析分析出来的指令的json字符串，类似于
        {
        "product_id": "mD97Vya1hi",
        "device_name": "d1",
        "params": {
            "led": true
        }
    }
    """

    def __init__(self, product_id: str, device_name: str, params: dict):
        self.product_id = product_id
        self.device_name = device_name
        self.params = params

    @classmethod
    def from_json(cls, json_data):
        # 检查是否需要解析 JSON 字符串
        if isinstance(json_data, str):
            # 将 JSON 字符串解析为字典
            data = json.loads(json_data)
        elif isinstance(json_data, dict):
            # 如果已经是字典格式，则直接使用
            data = json_data
        else:
            raise TypeError("json_data must be a str or dict")

        # 提取字段并创建 DeviceCtlDTO 实例
        return cls(
            product_id=data.get("product_id"),
            device_name=data.get("device_name"),
            params=data.get("params", {})
        )

    def __repr__(self):
        return f"DeviceData(product_id={self.product_id}, device_name={self.device_name}, params={self.params})"


